package com.gs.synedocket.fragment.docket;

import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.gs.synedocket.R;
import com.gs.synedocket.apiresult.ApiResultData;
import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.constant.EventCode;
import com.gs.synedocket.control.TitleView;
import com.gs.synedocket.db.bean.Event;
import com.gs.synedocket.db.dao.LogUtil;
import com.gs.synedocket.db.dto.DocketQcDto;
import com.gs.synedocket.db.sqlite.DBApi;
import com.gs.synedocket.dialog.LoadingDialogUtils;
import com.gs.synedocket.dialog.ToastDialogUtils;
import com.gs.synedocket.fragment.base.BaseSignFragment;
import com.gs.synedocket.presenter.DocketQcCheckPresenter;
import com.gs.synedocket.service.GpsService;
import com.gs.synedocket.util.DensityUtil;
import com.gs.synedocket.util.DocketUtil;
import com.gs.synedocket.util.SPUtil;
import com.gs.synedocket.view.IDocketQcCheckView;

import org.greenrobot.eventbus.EventBus;

public class DocketQcCheckFragment extends BaseSignFragment<IDocketQcCheckView, DocketQcCheckPresenter> implements IDocketQcCheckView {

    private LinearLayout llSign, llFail;
    private RadioButton rbSlump, rbTemperature, rbOvertimes, rbOther, rbSelect;
    private EditText etSlump, etTemperature, etOther;
    private RadioGroup rg;
    private boolean isPass;
    private Integer rejectReason;
    private String rejectRemak;
    private LinearLayout llCheck;
    private DocketQcDto mBean;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_docket_qc_check;
    }

    @Override
    protected DocketQcCheckPresenter createPresenter() {
        return new DocketQcCheckPresenter();
    }

    @Override
    protected void initView() {
        llCheck = fd(R.id.ll_check);
        TitleView viewCheck = fd(R.id.view_check);
        viewCheck.setContent(llCheck);
        viewCheck.setOnAnimEndListener(isOpen -> {
            if (isOpen) {
                EventBus.getDefault().post(new Event(EventCode.EVENT_SCROLLVIEW));
            }
        });
        llSign = fd(R.id.ll_sign);
        llFail = fd(R.id.ll_reject_reason);
        etSlump = fd(R.id.et_slump);
        etTemperature = fd(R.id.et_temperature);
        etOther = fd(R.id.et_other);
        rbSlump = fd(R.id.rb_slump);
        rbTemperature = fd(R.id.rb_temperature);
        rbOvertimes = fd(R.id.rb_overtimes);
        rbOther = fd(R.id.rb_other);
        MyRBOnCheckedChangeListener onCheckedChangeListener = new MyRBOnCheckedChangeListener();
        rbSlump.setOnCheckedChangeListener(onCheckedChangeListener);
        rbTemperature.setOnCheckedChangeListener(onCheckedChangeListener);
        rbOvertimes.setOnCheckedChangeListener(onCheckedChangeListener);
        rbOther.setOnCheckedChangeListener(onCheckedChangeListener);
        rg = fd(R.id.rg_check);
        rg.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
        btnUnSign.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {

    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void confirm() {
        if (rg.getCheckedRadioButtonId() == R.id.rb_fail) {
            isPass = false;
            if (rbSlump.isChecked()) {
                rejectReason = 1;
                rejectRemak = etSlump.getText().toString();
            } else if (rbTemperature.isChecked()) {
                rejectReason = 2;
                rejectRemak = etTemperature.getText().toString();
            } else if (rbOvertimes.isChecked()) {
                rejectReason = 3;
            } else if (rbOther.isChecked()) {
                rejectReason = 4;
                rejectRemak = etOther.getText().toString();
            } else {
                ToastDialogUtils.getInstance().showInfoMessage(context, R.string.sel_fail_reason);
                return;
            }
        } else {
            isPass = true;
        }
//        if (TextUtils.isEmpty(GpsUtil.getInstance().gps)) {
//            GpsUtil.getInstance().startLocation(getActivity());
//            Toast.makeText(context, R.string.gps_empty, Toast.LENGTH_LONG).show();
//            return;
//        }
        showLoading();
        // 判断需不需要拍照
        if (SPUtil.getInstance().getInt(AllConstants.TAKE_PHOTO,  getResources().getInteger(R.integer.take_photo)) == 1) {
            cameraUtil.takePhoto();
        }else {
            mPresenter.uploadBase64(mSignPhoto, null);
        }
    }

    @Override
    protected void submitReport() {

    }

    @Override
    protected void uploadReportPhoto(String url) {

    }

    @Override
    protected void takePhoto(String url) {
        mPresenter.uploadBase64(url, true);
    }

    @Override
    protected void captureError() {
        hideLoading();
    }


    @Override
    public void onUploadFileSuccess(ApiResultData<String> apiResult) {
        if (apiResult.getStatus() != 2000) {
            hideLoading();
            ToastDialogUtils.getInstance().showInfoMessage(context, apiResult.getMessage());
            return;
        }
        if (isTakePhoto) {
            isTakePhoto = false;
            mTakePhoto = apiResult.getData();
            mPresenter.uploadBase64(mSignPhoto, null);
        } else {
            uploadQcCheck(apiResult.getData());
        }
    }

    private void uploadQcCheck(String photo) {
        mBean = new DocketQcDto();
        mBean.setDocketId(DocketUtil.getInstance().getDocketId());
        mBean.setPhoto(photo);
        mBean.setPhoto1(mTakePhoto);
        if (isPass) {
            mBean.setState(1);
        } else {
            mBean.setState(0);
            mBean.setRejectReason(rejectReason);
            if (rejectReason == 4) {
                mBean.setRejectRemak(rejectRemak);
            } else {
                if (rejectReason != 3 && !TextUtils.isEmpty(rejectRemak)) {
                    mBean.setRejectVal(Double.parseDouble(rejectRemak));
                }
            }
        }
        mBean.setGps(GpsService.getGps());
        mBean.setGpsLoc(GpsService.getGpsLoc());
        mPresenter.qcCheck(mBean);
    }

    @Override
    public void onUploadFileFails(Exception e) {
        mBean = null;
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
    }

    @Override
    public void onQCCheckSuccess(ApiResultData<String> apiResultData) {
        if (apiResultData.getStatus() != 2000) {
            hideLoading();
            ToastDialogUtils.getInstance().showInfoMessage(context, apiResultData.getMessage());
            mBean = null;
            return;
        }
        LogUtil.getInstance().insertOrReplaceData(DocketUtil.getInstance().getDocketNo() + "-質檢成功");
        DocketUtil.getInstance().setQcState(isPass ? 1 : 0);
        if (!isPass) {
            DocketUtil.getInstance().setDriverState(4);
        }
        DBApi.getInstance().updateDocketState(mBean.getDocketId(), DocketUtil.getInstance().getDriverState());
        EventBus.getDefault().post(new Event(EventCode.EVENT_DONE_QC_CHECK, isPass));
        DBApi.getInstance().insetDocketQc(mBean);
        mBean = null;
    }

    private void refreshView() {
        if (rbSelect != null) {
            rbSelect.setChecked(false);
            rbSelect = null;
        }
        setNewHeight(llCheck, DensityUtil.displayViewHeight(llCheck) - DensityUtil.displayViewHeight(llFail) - DensityUtil.displayViewHeight(llSign));
        mBean = null;
        etTemperature.setText(null);
        etTemperature.setEnabled(false);
        etOther.setText(null);
        etOther.setEnabled(false);
        etSlump.setText(null);
        etSlump.setEnabled(false);
        clear();
        llSign.setVisibility(View.GONE);
        llFail.setVisibility(View.GONE);
        rg.setOnCheckedChangeListener(null);
        rg.clearCheck();
        rg.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
    }

    @Override
    public void onQCCheckFails(Exception e) {
        mBean = null;
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(context);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (llSign.getVisibility() == View.GONE) {
                llSign.setVisibility(View.VISIBLE);
            }
            if (checkedId == R.id.rb_pass) {
                llFail.setVisibility(View.GONE);
                setNewHeight(llCheck, DensityUtil.displayViewHeight(llCheck) - DensityUtil.displayViewHeight(llFail));
            } else {
                llFail.setVisibility(View.VISIBLE);
                setNewHeight(llCheck, DensityUtil.displayViewHeight(llCheck));
            }
            EventBus.getDefault().post(new Event(EventCode.EVENT_SCROLLVIEW));
        }
    }

    private void setNewHeight(View v, int height) {
        ViewGroup.LayoutParams lp = v.getLayoutParams();
        lp.height = height;
        v.setLayoutParams(lp);
    }

    class MyRBOnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                if (rbSelect != null) {
                    rbSelect.setChecked(false);
                }
                int id = buttonView.getId();
                if (id == R.id.rb_slump) {
                    etSlump.setEnabled(true);
                    etTemperature.setEnabled(false);
                    etTemperature.setText("");
                    etOther.setEnabled(false);
                    etOther.setText("");
                } else if (id == R.id.rb_temperature) {
                    etSlump.setEnabled(false);
                    etSlump.setText("");
                    etTemperature.setEnabled(true);
                    etOther.setEnabled(false);
                    etOther.setText("");
                } else if (id == R.id.rb_overtimes) {
                    etSlump.setEnabled(false);
                    etSlump.setText("");
                    etTemperature.setEnabled(false);
                    etTemperature.setText("");
                    etOther.setEnabled(false);
                    etOther.setText("");
                } else if (id == R.id.rb_other) {
                    etSlump.setEnabled(false);
                    etSlump.setText("");
                    etTemperature.setEnabled(false);
                    etTemperature.setText("");
                    etOther.setEnabled(true);
                }
                rbSelect = (RadioButton) buttonView;
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            refreshView();
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        photoPermissionsResult(requestCode, grantResults);
    }
}
